import { Component, ElementRef, OnInit, Output, Input, ViewChild, AfterViewInit, EventEmitter } from '@angular/core';
import { HttpModule } from '@angular/http';
import { HttpClientModule, HttpClient, HttpErrorResponse } from '@angular/common/http';

import { RouterModule, Router, ActivatedRoute } from '@angular/router';
import { Service } from '../../../server/server';
import { Pagination } from '../../../public/serve/pcrudInfo';
import { RemoveTableService } from '../../../public/serve/remove-table/remove-table.service';
import { CudTableService } from '../../../public/serve/cud-table/cud-table.service';
import { RoleRolebyComponent } from '../../../user/role/role-roleby/role-roleby.component';
import { HintsService } from '../../../public/serve/hints/hints.service';
declare var $: any;

interface Response {
  result: string[];
  result_code: string;
  message: string;
  length: number;
}

@Component({
  selector: 'app-role-table',
  templateUrl: './role-table.component.html'
})
export class RoleTableComponent implements OnInit {

  @Input() tableNumber : number;

  @Input() searchData: any;

  right: any = {
    "role": {},
  };
  constructor(
    private http: HttpClient, 
    private server: Service, 
    private router: Router, 
    private tableListService: CudTableService, 
    public removeTableService: RemoveTableService,
    private hintsService:HintsService  
  ) {
    this.right = $.extend(this.right, server.getRight());
    //console.log(this.right)
  }

  ngOnInit() {
    this.getTabList(1, 20, '0',this.searchData);
    this.roleslist();

    //接受查询结果
    // this.server.roleeventEmit.subscribe((value: any) => {
    //   this.tabVal = value;
    //   //console.log(this.tabVal)
    // });
  }


  @Output()
  tabeListOutput: EventEmitter<string> = new EventEmitter();

  public tabVal: any;
  public rolesData: any[];
  // 表格
  getTabList(pageNumber, pageSize, id,queryCriteria) {
    let url = this.server.baseUrl+'admin/roles/getList';
    let data = {pageNumber:pageNumber,pageSize:pageSize,id:id,queryCriteria:queryCriteria}

    this.tableListService.postRequest(url, data).then((data: any) => {
      if(data.result_code == '0000') {
        this.tabVal = data.result;
        this.tabeListOutput.emit(data.length);
      }
      //console.log(this.tabVal);
    }).catch();
  }

  //roles list
  roleslist() {
    return this.http.post<Response>(this.server.baseUrl+'admin/roles/getRoleGroupsList', {})
      .subscribe(res => {
        if(res.result_code == '0000') {
          this.rolesData = res.result;
          this.server.rolesdataeeventEmit.emit(this.rolesData)
        }
        //console.log(this.rolesData)
      });
  }

  @Output()
  detailsOutput: EventEmitter<roleype> = new EventEmitter();

  // 详情（弹窗），用于展示默认数据
  detailsPopup(tabval) {
    $("#details").modal("show");
    this.outputTabVal(tabval);
    //console.log(tabval)
  }
  // 每一行的表格信息
  outputTabVal(tabval) {
    let tabVal: roleype = {
      //createUserId: '',
      roleGroupName: tabval.roleGroupName,
      roleGroupId: tabval.roleGroupId,
      description: tabval.description,
      roleName: tabval.roleName,
      roleId: tabval.roleId,
      roleCode: tabval.roleCode,
      autoAssignment: tabval.autoAssignment
    };
    this.detailsOutput.emit(tabVal);
  }

  public roleselectId = { roleId: '', roleGroupId: '', roleGroupName: '', roleName: '', description: '', autoAssignment: '', roleCode: '' };
  public body:roleype = { roleId: "", roleGroupId: "", roleGroupName: "", roleName: "", description: "", autoAssignment: "", roleCode: "" };
  //focus
  role_focus(selectId) {
    //console.log("用户输入")
    this.roleselectId = selectId;
    //console.log(this.roleselectId)
    this.body = {
      roleId: this.roleselectId.roleId,
      roleGroupId: this.roleselectId.roleGroupId,
      roleGroupName: this.roleselectId.roleGroupName,
      roleName: this.roleselectId.roleName,
      description: this.roleselectId.description,
      autoAssignment: this.roleselectId.autoAssignment,
      roleCode: this.roleselectId.roleCode
    };
    //return this.rolesselectId;
  }
  //autoclick
  autoclick(selectId) {
    //console.log("选择框触发")
    this.roleselectId = selectId;
    this.body = {
      roleId: this.roleselectId.roleId,
      roleGroupId: this.roleselectId.roleGroupId,
      roleGroupName: this.roleselectId.roleGroupName,
      roleName: this.roleselectId.roleName,
      description: this.roleselectId.description,
      autoAssignment: this.roleselectId.autoAssignment,
      roleCode: this.roleselectId.roleCode
    };
    //console.log(this.body)
    this.role_blur();
  }
  //主键单选
  // public primaryKeymin(val,i) {
  //   for (let k in this.tabVal) {
  //     this.tabVal[k].autoAssignment = false;
  //   }
  //   this.tabVal[i].autoAssignment = true;
  //   this.autoclick(val);
  //   console.log(this.tabVal)
  // }
  //blur
  //验证字符是否通过
  public checktext: any;
  role_blur() {
    //console.log("失去焦点")

    var check = /^[a-zA-Z\d\u4E00-\u9FA5_]+$/
    if (check.test(this.body.roleName) || this.body.roleName == '') {
      this.checktext = true;
    } else {
      this.checktext = false;
    }
    if (this.body.roleGroupId !== '' && this.body.roleGroupName !== '' && this.body.autoAssignment !== '' && this.body.roleGroupName !== '' && this.body.roleName !== '' && this.checktext) {
     // console.log(this.body)
      this.body.autoAssignment = Number(this.body.autoAssignment);
      this.http.post<Response>(this.server.baseUrl+'admin/roles/modify', this.body)
        .subscribe(res => {
          //console.log(res)
          if (res.result_code = '0000') {
            
            this.body = {
              roleId: "",
              roleGroupId: "",
              roleGroupName: "",
              roleName: "",
              description: "",
              autoAssignment: "",
              roleCode: ""
            };
            this.hintsService.messages(res.message,res.result_code);
            this.getTabList(1, 20, '0',this.searchData);
            this.roleslist();
            //console.log( this.server.prompt)
          } else {
            this.hintsService.messages(res.message,res.result_code);
            this.getTabList(1, 20, '0',this.searchData);
            this.roleslist();
          }
        });
    } else {
      if (this.inputnull == '' || this.checktext == false) {
        //console.log("提交数据为空...");
        this.hintsService.messages("必填项不能修改为空,不能输入特殊字符,允许输入_","9999");
        this.getTabList(1, 20, '0',this.searchData);
        this.roleslist();
      }
    }


  }
  //input null
  public inputnull: any;
  checkname(event) {
    this.inputnull = event;
  }

  @ViewChild(RoleRolebyComponent)
  public roleRoleby: RoleRolebyComponent;

  //get Id
  public roleId: string;
  public timeout;
  public getRoleId(roleId): void {
    $("#roleby").modal("show");
    this.roleId = roleId;
    this.server.rolebyeventEmit.emit(this.roleId)
    //console.log(this.roleId)
  }


  public getRoleLimit(roleId): void {
    $("#permissionAssignment").modal("show");
    this.roleId = roleId;
    this.server.rolebyeventEmit.emit(this.roleId)
    //console.log(this.roleId)
  }
  public getRoleLimit1(roleId): void {
    //$("#permissionAssignment").modal("show");
    this.roleId = roleId;
    this.server.rolebyeventEmit.emit(this.roleId)
    //console.log(this.roleId)
  }

  //批量删除
  // 全选
  public isSelectAll: boolean = false;
  public isChose: boolean = false;
  public isSelect: boolean = true;
  public isDisable: any;              // 按钮（启用/禁用）

  @Output() isSelectFromTable = new EventEmitter<boolean>();

  selectAll(bool, tabVal) {
    console.log(this.isSelectAll,this.isChose)
    this.isSelectAll = this.isChose = this.removeTableService.removeAll(bool, tabVal, 'roleId');
    this.isSelect = !this.isSelectAll;
    this.isSelectFromTable.emit(this.isSelect);
    console.log(this.isSelectAll,this.isChose)
  }

  // 单选（多选）
  chose(bool, roleId, length) {
    console.log(bool,roleId,length)
    this.isDisable = this.removeTableService.removeChose(bool, roleId, length);
    this.isSelectAll = this.isDisable.bool;
    this.isDisable.len ? this.isSelect = false : this.isSelect = true;
    this.isSelectFromTable.emit(this.isSelect);
  }

  // 没有数据时取消勾选全选按钮
  cancelSelectAll() {
    this.isSelectAll = false;
    this.isChose = false;
  }

}

export class roleype {
  //public createUserId: string;
  public roleName: string;
  public roleId: string;
  public roleGroupName: string;
  public roleGroupId: string;
  public roleCode: string;
  public description: string;
  public autoAssignment: any;
}
